package com.yang.controller;

import com.yang.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 绑定默认角色（普通用户）
     */
    @PostMapping("/bindDefaultRole/{userId}")
    @Transactional
    public String bindDefaultRole(@PathVariable Long userId) {
        try {
            permissionService.bindDefaultRole(userId);
            return "默认角色绑定成功";
        } catch (Exception e) {
            return "绑定失败：" + e.getMessage();
        }
    }

    /**
     * 查询用户角色码
     */
    @GetMapping("/roleCode/{userId}")
    @Transactional
    public String getUserRoleCode(@PathVariable Long userId) {
        try {
            String roleCode = permissionService.getUserRoleCode(userId);
            return roleCode != null ? roleCode : "用户角色不存在";
        } catch (Exception e) {
            return "查询失败：" + e.getMessage();
        }
    }

    /**
     * 升级用户为管理员（超管调用）
     */
    @PostMapping("/upgradeToAdmin/{userId}")
    @Transactional
    public int upgradeToAdmin(@PathVariable Long userId) {
       return permissionService.upgradeToAdmin(userId);
    }

    /**
     * 降级用户为普通角色（超管调用）
     */
    @PostMapping("/downgradeToUser/{userId}")
    @Transactional
    public int downgradeToUser(@PathVariable Long userId) {
        return permissionService.downgradeToUser(userId);
    }
}
